package com.xuhuan.practice.interceptors;

import com.xuhuan.practice.utils.JwtUtil;
import com.xuhuan.practice.utils.RedisUtil;
import com.xuhuan.practice.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: huan.xu
 * @create: 2024/6/10 21:01
 * @description:
 **/
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) {
    log.info("进入令牌校验，请求地址:{}", request.getRequestURI());
    String token = request.getHeader("Authorization");
    try {
      String redisToken = RedisUtil.getStringKey(token);
      if(StringUtils.isBlank(redisToken)){
        throw new RuntimeException("token已失效");
      }
      Map<String, Object> claims = JwtUtil.parseToken(token);
      ThreadLocalUtil.set(claims);
      return true;
    } catch (Exception e) {
      response.setStatus(401);
      log.error("拦截校验令牌失败:{}", ExceptionUtils.getStackTrace(e));
    }
    return false;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
    ThreadLocalUtil.remove();
  }
}
